package logic

import (
	"errors"
	"fmt"
	"woanju/dao/mysql"
	"woanju/models"
	"woanju/pkg/email"
	snowflake "woanju/pkg/snowflask"
)

func GuardianInfo(g *models.Guardian, username string) (*models.Guardian, error) {
	//判断监护对象是否存在
	err := mysql.CheckUserExist(username)
	if !errors.Is(err, mysql.ErrorUserExist) {
		return nil, err
	}

	//判断监护人是否已存在，存在就修改，不存在插入新的
	err = mysql.CheckGuardianExist(g.UserID)
	if errors.Is(err, mysql.ErrorGuardianNotExist) {
		//生成guardian_id
		gid := snowflake.GenID()
		g.GuardianID = gid
		//mysql插入监护人信息

		err := mysql.InsertGuardian(g)
		if err != nil {
			return nil, err
		}
		if err := email.MainSendEmail(g.GuardianName, username, g.Email, 3); err != nil {
			return nil, err
		}
		return g, nil
	} else if errors.Is(err, mysql.ErrorGuardianExist) {
		fmt.Println("222222")

		err := mysql.UpdateGuardian(g)
		if err != nil {
			return nil, err
		}
		if err := email.MainSendEmail(g.GuardianName, username, g.Email, 3); err != nil {
			return nil, err
		}
		return g, nil
	} else {
		return nil, err
	}

}

func Warn(uid int64, uname string) error {
	//1.查看监护人是否存在
	err := mysql.CheckGuardianExist(uid)
	if !errors.Is(err, mysql.ErrorGuardianExist) {
		return err
	}

	//2.拿到监护人的邮件
	g, err := mysql.GetGuardianInfo(uid)
	if err != nil {
		return err
	}

	return email.MainSendEmail(g.GuardianName, uname, g.Email, 2)
}
